/**
 * 缺卡记录
 */
import React, { Fragment } from 'react';
import { Card, Form, Table, Row, Col, Button } from 'antd';
import { get as getPath } from 'object-path';
import { QuickForm, utils } from 'vv-frontend-components';
import { connect } from 'umi';
import { history } from 'umi';
import { formatMessage } from 'umi';
import LinkTo from '@/components/LinkTo';
import Locale from '@/utils/locale';
import { download } from '@/utils/utils';
import AuthComponent from '@/utils/auth/AuthComponent';
import { Pagination } from '@/components';
import styles from './index.less';

const { deepTrim } = utils;
class MissList extends React.Component {
    column = [
        {
            title: `${formatMessage({
                id: 'stat.absenceList.userNo'
            })}`,
            dataIndex: 'userNo',
            key: 'userNo',
            width: 100
        },
        {
            title: `${formatMessage({
                id: 'stat.absenceList.userName'
            })}`,
            dataIndex: 'userName',
            key: 'userName',
            width: 100,
            render: (text, record) => {
                const { applicationNo, userName } = record;
                return this.goToFlow(applicationNo, userName, 'name');
            }
        },
        {
            title: `${formatMessage({
                id: 'stat.absenceList.departName'
            })}`,
            dataIndex: 'departName',
            key: 'departName',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {text}
                </div>
            )
        },
        {
            title: `${formatMessage({
                id: 'stat.miss.typeNick'
            })}`,
            dataIndex: 'typeNick',
            key: 'typeNick',
            width: 150,
            filters: []
        },
        {
            title: `${formatMessage({
                id: 'stat.miss.lackTime'
            })}`,
            dataIndex: 'lackTime',
            key: 'lackTime',
            width: 200,
            render: (text, record) => <span>{record.lackTime}</span>,
            sorter: () => {}
        },
        {
            title: `${formatMessage({
                id: 'stat.missList.statusNick'
            })}`,
            dataIndex: 'statusNick',
            key: 'statusNick',
            width: 100,
            filters: [],
            render(text, record) {
                const dictColor = {
                    1: 'rgba(0,0,0,0.65)',
                    2: '#F5222D'
                };
                return <span style={{ color: dictColor[record.status] }}>{record.statusNick}</span>;
            }
        },
        {
            title: `${formatMessage({
                id: 'stat.miss.reissueTime'
            })}`,
            dataIndex: 'reissueTime',
            key: 'reissueTime',
            width: 200,
            render: (text, record) => <span>{record.reissueTime ? record.reissueTime : '--'}</span>,
            sorter: () => {}
        },
        {
            title: `${formatMessage({
                id: 'stat.miss.applicationNo'
            })}`,
            dataIndex: 'applicationNo',
            key: 'applicationNo',
            render: (text, record) => {
                const { applicationNo } = record;
                return this.goToFlow(applicationNo, applicationNo, 'applicationNo');
            }
        },
        {
            title: `${formatMessage({
                id: 'stat.absence.action'
            })}`,
            dataIndex: 'action',
            key: 'action',
            width: 120,
            fixed: 'right',
            render: (text, record) => (
                <LinkTo
                    to="/office/personnelManagement/attendance/timetag/attendRecord/clockRecord"
                    query={{
                        id: record.employeeCode,
                        name: record.userName,
                        startTime: record.lackDate,
                        endTime: record.lackDate
                    }}
                >
                    {formatMessage({
                        id: 'stat.absence.seeDetail'
                    })}
                </LinkTo>
            )
        }
    ];

    ORDER_MAP = {
        'reissue_time asc': 'ascend',
        'reissue_time desc': 'descend',
        'lack_time asc': 'ascend',
        'lack_time desc': 'descend'
    };

    constructor(props) {
        super(props);
        const { location } = this.props;
        const { query } = location;

        this.state = {
            lackStatus: [],
            lackType: [],
            orderByField: query.orderByField,
            sorter: '',
            filter: '',
            forceRefresh: false
        };
    }

    componentDidMount() {
        const { location } = this.props;
        const { query } = location;
        const { orderByField, lackType = [], lackStatus = [] } = query;

        this.column[4].sortOrder = this.transformSortOrder('lack_time', orderByField);
        this.column[6].sortOrder = this.transformSortOrder('reissue_time', orderByField);

        const defaultType = Array.isArray(lackType) ? lackType : [lackType];
        const defaultStatus = Array.isArray(lackStatus) ? lackStatus : [lackStatus];

        this.setState(
            {
                lackType: defaultType,
                lackStatus: defaultStatus
            },
            () => {
                this.getTypeListAll();
                this.fetchList();
            }
        );
    }

    goToFlow = (applicationNo, text, type) => {
        const isOldFlow = !applicationNo.includes('-');
        const url = isOldFlow
            ? '/office/institutions/flowManage/fullApprovalProcess/processDetail'
            : '/personal/portal/myAuditRead/myAuditReadDetail';
        const params = isOldFlow ? { applicationNo, linkFrom: '1' } : { applicationNo };
        const t = type === 'name' ? text : '--';
        return (
            <span>
                {applicationNo ? (
                    <LinkTo to={url} query={params}>
                        {text}
                    </LinkTo>
                ) : (
                    t
                )}
            </span>
        );
    };

    transformSortOrder = (currentField = '', orderByField = '') => {
        const [field] = orderByField.split(' ');
        if (field !== currentField) {
            return false;
        }
        return this.ORDER_MAP[orderByField];
    };

    getParams = _query => {
        const { form, location } = this.props;
        const { query } = location;
        const { getFieldsValue } = form;
        const { companyDepart = {}, date = { range: [] }, userName } = getFieldsValue();

        const param = {
            ...query,
            companyCode: companyDepart?.companyId || '',
            departmentCode: companyDepart?.departmentId || '',
            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            employeeName: userName || '',
            pageNo: query.pageNo || 1,
            pageSize: query.pageSize || 10,
            orderByField: getPath(this.state, 'orderByField', ''),
            lackStatus: getPath(this.state, 'lackStatus', []),
            lackType: getPath(this.state, 'lackType', []),
            ..._query
        };
        return param;
    };

    // 获取列表
    fetchList = query => {
        const { dispatch } = this.props;
        dispatch(
            deepTrim({
                type: 'abnormalRank/fetchMylack',
                payload: this.getParams(query)
            })
        );
    };

    handleSubmit = async e => {
        e.preventDefault();
        const { location, form } = this.props;
        const { getFieldsValue } = form;
        const { query, pathname } = location;
        const { date = {} } = getFieldsValue();
        const { type, quarter } = date;
        history.push({
            pathname,
            query: {
                ...query,
                ...this.getParams(),
                pageNo: 1,
                dateType: type,
                quarter,
                key: 'misslist'
            }
        });

        this.fetchList();
    };

    /** 导出 */
    handelExport = () => {
        const { pageNo, pageSize, ...other } = this.getParams();
        const { dispatch } = this.props;
        download({
            getData: () =>
                dispatch({
                    type: 'abnormalRank/fetchLackeExport',
                    payload: deepTrim(other)
                })
        });
    };

    // 表格表头点击切换排序
    changeTable = async (pagination, filters, sorters) => {
        const { filter = {}, sorter } = this.state;
        let orderBy;
        let sorterField;

        if (sorters && sorters.field && sorters.order) {
            if (sorters.field === 'lackTime') {
                sorterField = 'lack_time';
            }
            if (sorters.field === 'reissueTime') {
                sorterField = 'reissue_time';
            }
            const order = sorters.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
            this.setState({
                orderByField: orderBy
            });
        } else if (typeof sorters === 'string') {
            this.setState({
                orderByField: ''
            });
        }

        if (filters && JSON.stringify(filter) !== JSON.stringify(filters)) {
            this.setState({
                filter: filters
            });
        }

        if (sorters && sorters !== sorter) {
            this.setState({
                sorter: sorters,
                orderByField: orderBy
            });
        }

        this.column[3].filteredValue = getPath(filters, 'typeNick') || filter.typeNick;
        this.column[5].filteredValue = getPath(filters, 'statusNick') || filter.statusNick;
        this.column[4].sortOrder = this.transformSortOrder('lack_time', orderBy);
        this.column[6].sortOrder = this.transformSortOrder('reissue_time', orderBy);

        this.setState(
            {
                lackStatus: getPath(filters, 'statusNick') || filter.statusNick,
                lackType: getPath(filters, 'typeNick') || filter.typeNick
            },
            () => {
                history.push({ query: { ...this.getParams(), pageNo: 1 } });
                setTimeout(() => {
                    this.fetchList();
                });
            }
        );
    };

    changePagination = _pagination => {
        const { location } = this.props;
        const { query } = location;
        history.push({ query: { ...query, pageNo: _pagination.current, pageSize: _pagination.pageSize } });
        setTimeout(() => {
            this.fetchList();
        });
    };

    getTypeListAll = () => {
        const { dispatch } = this.props;
        const param = {
            dictCode: 'lackStatus'
        };
        const param2 = {
            dictCode: 'lackType'
        };
        dispatch({
            type: 'abnormalRank/fetchTypeList',
            payload: param,
            callback: () => {
                dispatch({
                    type: 'abnormalRank/fetchLackTypeList',
                    payload: param2,
                    callback: () => {
                        this.setFilter();
                    }
                });
            }
        });
    };

    // 类型/是否-筛选
    setFilter = () => {
        const { abnormalRank } = this.props;
        const { typeList, lackTypeList } = abnormalRank;

        const lackStatus = [];
        const lackType = [];
        for (let index = 0; index < typeList.length; index += 1) {
            const list = {
                text: typeList[index].dictName,
                value: typeList[index].dictValue
            };
            lackStatus.push(list);
        }
        for (let index = 0; index < lackTypeList.length; index += 1) {
            const list = {
                text: lackTypeList[index].dictName,
                value: lackTypeList[index].dictValue
            };
            lackType.push(list);
        }
        this.column[3].filters = lackType;
        this.column[5].filters = lackStatus;
        this.column[3].filteredValue = this.state.lackType;
        this.column[5].filteredValue = this.state.lackStatus;

        this.setState({ forceRefresh: true });
    };

    render() {
        const { loading, abnormalRank, form, authCode, location } = this.props;
        const { query } = location;
        const { missData, paginationMiss } = abnormalRank;
        const { locale } = new Locale('stat.overtime');

        return (
            <Fragment>
                <Form layout="inline" onSubmit={this.handleSubmit}>
                    <Card
                        className={styles.bordered}
                        bordered={false}
                        title={formatMessage({
                            id: 'stat.miss.title'
                        })}
                        headStyle={{ padding: '0' }}
                        bodyStyle={{ padding: '16px 0' }}
                        extra={
                            <Fragment>
                                <Button type="primary" htmlType="submit">
                                    {locale('form.search', false)}
                                </Button>
                                <AuthComponent code={authCode}>
                                    <Button
                                        onClick={this.handelExport}
                                        style={{ marginLeft: '10px' }}
                                        disabled={loading}
                                    >
                                        导出
                                    </Button>
                                </AuthComponent>
                            </Fragment>
                        }
                    >
                        <Row type="flex" className="searchTitle">
                            <Col className={styles.quickFormPadding}>
                                <QuickForm form={form} config={getPath(this.props, 'config')} />
                            </Col>
                        </Row>
                    </Card>
                </Form>
                <Card bordered={false} className={styles.cardAbnorRank}>
                    <Table
                        dataSource={missData}
                        columns={this.column}
                        loading={loading}
                        rowKey="id"
                        onChange={this.changeTable}
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                    />
                    <Pagination
                        onChange={this.changePagination}
                        total={paginationMiss.total}
                        current={query.pageNo}
                        pageSize={query.pageSize}
                        loading={loading}
                    />
                </Card>
            </Fragment>
        );
    }
}

export default connect(({ abnormalRank, loading }) => ({
    abnormalRank,
    loading: loading.models.abnormalRank
}))(Form.create()(MissList));
